package org.catspaw.cherubim.matcher;

import java.util.HashMap;
import java.util.Map;

import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

/**
 * 用Perl5正则表达式模式匹配目标字符串
 * @author 孙宁振
 */
public class Perl5RegexStringMatcher extends AbstractStringMatcher {

	private PatternMatcher			patternMatcher	= new Perl5Matcher();	//url匹配器
	private Perl5Compiler			compiler		= new Perl5Compiler();
	private boolean					usePatternCache;
	private Map<String, Pattern>	cache;

	public Perl5RegexStringMatcher() {
	}

	public Perl5RegexStringMatcher(boolean usePatternCache) {
		this.usePatternCache = usePatternCache;
		if (usePatternCache) {
			cache = new HashMap<String, Pattern>();
		}
	}

	/**
	 * 判断指定资源描述符和指定目标字符串是否匹配
	 * @param pattern 资源描述符
	 * @param target 目标字符串
	 * @return 是否匹配
	 */
	public boolean match(String pattern, String target) {
		Pattern compiledPattern = null;
		if (usePatternCache) {
			compiledPattern = cache.get(pattern);
		}
		if (compiledPattern == null) {
			compiledPattern = compilePattern(pattern);
			if (usePatternCache) {
				cache.put(pattern, compiledPattern);
			}
		}
		return match(compiledPattern, target);
	}

	public boolean match(Pattern pattern, String target) {
		return patternMatcher.matches(target, pattern);
	}

	public Pattern compilePattern(String pattern) {
		Pattern compiledPattern;
		try {
			compiledPattern = compiler.compile(pattern,
												Perl5Compiler.READ_ONLY_MASK);
		} catch (MalformedPatternException mpe) {
			throw new IllegalArgumentException("Malformed regular expression: "
					+ pattern);
		}
		return compiledPattern;
	}

	public Perl5Compiler getCompiler() {
		return compiler;
	}

	public PatternMatcher getPatternMatcher() {
		return patternMatcher;
	}
}
